Homework Assignment

Your task this week is to make a program named "fizzbuzz". The rules

  • Your program should go through the numbers 1 to 100,
  • if the number is even, print "fizz"
  • if the number is divisible by 5 print "buzz"
  • if the number is both even and divisible by 5 print "fizzbuzz"
  • otherwise just print the number.

For extra points:

For extra points you need to make your code easily modifiable. I want to be able to:

  • change the string printed out (e.g change 'fizz' to 'dave', or some other string)
  • be able to change the total
  • change one(or both) of the rules (e.g. change the rule to be divisible by 6, not 5)

However, I am a stupid robot that can only type 3 characters at a time. Therefore, to modify your code I cannot go inside it and change stuff by myself. I need you to guide my hand all the way. *(Hint you should use Pythons "input" Function).

Possible solution #1 (easy)


In [3]:
for number in range(1,101): # remember, end point is exclusive
    fizz = "fizz" if number % 2 == 0 else False
    buzz = "buzz" if number % 5 == 0 else False 
    
    if fizz and buzz:
        print(fizz + buzz)
    elif fizz:
        print(fizz)
    elif buzz:
        print(buzz)
    else:
        print(number)


1
fizz
3
fizz
buzz
fizz
7
fizz
9
fizzbuzz
11
fizz
13
fizz
buzz
fizz
17
fizz
19
fizzbuzz
21
fizz
23
fizz
buzz
fizz
27
fizz
29
fizzbuzz
31
fizz
33
fizz
buzz
fizz
37
fizz
39
fizzbuzz
41
fizz
43
fizz
buzz
fizz
47
fizz
49
fizzbuzz
51
fizz
53
fizz
buzz
fizz
57
fizz
59
fizzbuzz
61
fizz
63
fizz
buzz
fizz
67
fizz
69
fizzbuzz
71
fizz
73
fizz
buzz
fizz
77
fizz
79
fizzbuzz
81
fizz
83
fizz
buzz
fizz
87
fizz
89
fizzbuzz
91
fizz
93
fizz
buzz
fizz
97
fizz
99
fizzbuzz

Possible Solution #2 (Hard)


In [1]:
msg_1 = input("please give me a string to replace 'fizz' with " )
msg_2 = input("please give me a string to replace 'buzz' with ")
game_length = int(input("we should go up to the number..."))

mod_1 = int(input("{} should be divisble by...".format(msg_1)))
mod_2 = int(input("{} should be divisible by...".format(msg_2)))

print("LET THE GAMES BEGIN!")

for number in range(1, game_length + 1):
    
    rule_1 = msg_1 if number % int(mod_1) == 0 else False
    rule_2 = msg_2 if number % int(mod_2) == 0 else False
    
    if rule_1 and rule_2:
        print(rule_1 + rule_2)
    
    elif rule_1 and not rule_2:
        print(rule_1)
    
    elif rule_2 and not rule_1:
        print(rule_2)
    
    else:
        print(number)


please give me a string to replace 'fizz' with dave
please give me a string to replace 'buzz' with jerry
we should go up to the number...24
dave should be divisble by...2
jerry should be divisible by...7
LET THE GAMES BEGIN!
1
dave
3
dave
5
dave
jerry
dave
9
dave
11
dave
13
davejerry
15
dave
17
dave
19
dave
jerry
dave
23
dave

In [ ]: